<template>
    <el-container direction="vertical" class="vertical">
        <el-main class="el-main">
            <div>
                <el-form size="default" :inline="true" class="tm">
                    <el-form-item>
                        <el-select-v2 :style="{ width: '200px' }" v-model="userids" :options="getusers" filterable>
                        </el-select-v2>
                    </el-form-item>
                    <el-form-item label="比赛名称">
                        <el-select v-model="activityid" placeholder="请选择" filterable clearable>
                            <el-option v-for="(v, i) in activity" :key="'team_' + i" :label="v.name" :value="Number(v.ID)">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item class="text-right">
                        <el-button type="primary" @click="start">查询</el-button>
                        <el-button type="primary" v-if="Number(data.grade) > 1" @click="() => download()">下载</el-button>
                        <el-button type="primary" v-if="Number(data.grade) > 1"
                            @click="() => download(true)">下载全部</el-button>
                    </el-form-item>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="总条数:">{{ count1 }} &nbsp;&nbsp;&nbsp;</el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <div class="data2div" v-if="count1">
                <el-table class="data2table" :row-class-name="tableRowClassName" :data="userquestion" style="width: 100%">
                    <el-table-column prop="user.name" label="团队成员" width="100">
                        <template #default="scope">
                            <router-link v-slot="{ href }" custom :to="{
                                name: '用户',
                                query: { userid: scope.row.userid },
                            }">
                                <el-link :href="href">{{ scope.row.user.name }}
                                </el-link>
                            </router-link>
                        </template>
                    </el-table-column>
                    <el-table-column prop="matchquestion.name" label="题目名称"></el-table-column>
                    <el-table-column prop="createdAt" label="答题时间" :formatter="({ createdAt }) => TimeYH1(createdAt)"
                        width="100"></el-table-column>
                    <el-table-column prop="type" label="类型" width="72"></el-table-column>
                    <el-table-column prop="resultdata" label="AC" width="123">
                        <template #default="scope">
                            <div v-if="scope.row.type === '代码'">
                                <span v-text="ALLTYPE[scope.row.resultdata ? scope.row.resultdata : 'WT'][1]"
                                    :class="ALLTYPE[scope.row.resultdata ? scope.row.resultdata : 'WT'][1]"></span>
                            </div>
                            <div v-else>{{ scope.row.resultdata ? scope.row.resultdata : '错误' }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="result" label="测试点" width="200">
                        <template #default="scope">
                            <div v-if="Array.isArray(scope.row.resultdataarr)">
                                <span :style="{ width: '50px', display: 'inline-block' }"
                                    v-for="(v, key) in acgroup(scope.row.resultdataarr)" :key="'a_' + key">
                                    <span :class="ALLTYPE[v[0]][1]">{{ v[0] }}</span>
                                    <span>:{{ v[1] }}</span>
                                </span>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="result" label="其他信息" width="72">
                        <template #default="scope">
                            <span class="cu" v-if="iscode" @click="down(scope.row)">下载源码</span>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </el-main>
        <el-footer class="text-right pt-2 pl-3" v-if="count1">
            <el-pagination :page-size="limit" :total="count1" @current-change="change" layout="prev, pager, next"
                :current-page="Math.floor(offset / limit) + 1"></el-pagination>
        </el-footer>
        <el-empty v-if="!count1" image="https://cdn.hterobot.com/JOY/oj_1_1/Not%20Found%20illustration.png" />

    </el-container>
</template>


<script setup lang="ts">
import { ElMessage } from "element-plus";
import { countBy, once, pairs } from "underscore";
import { computed, inject, onMounted, onUnmounted, ref, watch } from "vue";
import { onBeforeRouteUpdate, useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";
import { Iobj, Iteamselectmatchuserquestionnbody, asyncteamselectactivity, asyncteamselectmatchuserquestion } from "../../../api";
import { Storekey } from "../../../interface";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import { getExceltodownload } from "../../../util/excel";
import { ALLTYPE } from "@/util/jianchatime";
import { TimeYH, TimeYH1 } from "../../../util/time";

const prop = defineProps<{ formdata: { teamid?: number, userid?: number, formdate: Date, todate: Date }, teamusers: Studycodemodel.Iteamuser[], data: Studycodemodel.Iteam, isAdmin: number }>()

const activityid = ref<number>()

const userquestion = ref<Studycodemodel.Imatchuserquestion[]>([]);
const route = useRoute();
const router = useRouter();
const roue = computed(() => {
    return route.query;
});
const count1 = ref(0);
const order = computed(() => {
    return roue.value.order || "ID";
});

const store = useStore(Storekey);
const getteam = computed<Studycodemodel.Iteam[]>(() => {
    return store.getters.getteam;
});

const iscode = computed(() => {
    if (!prop.data.iscode) {
        return true
    } else {
        if (prop.isAdmin) {
            return true
        }
    }
    return false
})


function acgroup(data?: Array<keyof Studycodemodel.IALLTYPE>) {
    if (Array.isArray(data)) {
        const c = countBy(data, (a) => {
            return a
        })
        return pairs(c)
    }
    return []
}


const getusers = computed(() => {
    if (prop.data.isadminshowactivity) {
        return [{ value: 0, label: '全部成员' }, ...prop.teamusers.map(e => { return { value: Number(e.user?.ID), label: String(e.user?.name) } })]

    } else {
        return [{ value: 0, label: '全部成员' }, ...prop.teamusers.filter(t => !t.isAdmin).map(e => { return { value: Number(e.user?.ID), label: String(e.user?.name) } })]
    }
})
const headnavdialogVisible = inject("headnavdialogVisible", () => { });
const user = computed(() => {
    return store.state.user;
});
const times = computed(() => [prop.formdata.formdate, prop.formdata.todate]);
const height = ref(window.innerHeight - 74);
function onresize(e: UIEvent) {
    height.value = window.innerHeight - 74;
}
window.onresize = onresize;

const offset = computed(() => {
    return Number(roue.value.offset) || 0;
});
const isad = computed(() => {
    return Number(roue.value.isad) || 0;
});
const limit = computed(() => {
    return Number(roue.value.limit) || 20;
});
const questionid = ref<number | null>();
const teamid = computed(() => {
    return prop.formdata.teamid
});
const userids = ref<number>(0);

onUnmounted(() => {
    window.onresize = () => { };
});

onBeforeRouteUpdate(() => {
    questionid.value = Number(roue.value.questionid) || null;
});

watch(
    () => route.query,
    () => {
        start();
    }
);

const activity = ref<Studycodemodel.Iactivity[]>([])

watch(() => prop.teamusers, () => {
    start()
})

onMounted(async () => {
    if (prop.isAdmin) {
        const { rows } = await asyncteamselectactivity({
            teamid: prop.data?.ID,
        })
        activity.value = rows
        activityid.value = Number(route.query.activityid) || undefined
        start().then(e => {
            router.push({ query: {} })
        })
    }
})


function tableRowClassName({ row, rowIndex }: any) {
    if (rowIndex % 2 === 1) {
        return "warning-row";
    } else {
        return "success-row";
    }
}
async function start() {
    if (!user.value) {
        headnavdialogVisible();
        return;
    }

    const userid = userids.value;
    // if (!activityid.value) {
    //     return
    // }
    const formquery: Iobj<Iteamselectmatchuserquestionnbody> = {
        _limit: limit.value,
        _offset: offset.value,
        teamid: prop.data?.ID,
        activityid: activityid.value
    };
    if (userid) {
        formquery.userid = userid;
    } else {
        formquery.userid = getusers.value.map(e => e.value).filter(e => e)
    }
    if (times.value) {
        formquery.createdAt = {
            lt: times.value[1],
            gt: times.value[0],
        };
    }

    if (questionid.value) {
        Object.assign(formquery, {
            questionid: questionid.value,
        });
    }
    const { rows, count } = await asyncteamselectmatchuserquestion(
        Object.assign(formquery)
    );
    count1.value = count;
    userquestion.value = rows
}


function change(r: number) {
    router.push({
        query: {
            limit: limit.value,
            order: order.value,
            offset: (r - 1) * limit.value,
        },
    });
}
const onc = once(start);

function down(row: Studycodemodel.Imatchuserquestion) {
    const { context, language } = row;
    if (context) {
        let t = ".cpp";
        if ("c" === language) {
            t = ".c";
        }
        if ("python" === language) {
            t = ".py";
        }
        const bo = new File(
            [context],
            row.user?.name + "_" + row.matchquestion?.name + t,
            {
                type: "text/plain",
            }
        );
        var a = document.createElement("a");
        a.download = row.user?.name + "_" + row.matchquestion?.name + t;
        a.href = URL.createObjectURL(bo);
        a.click();
    } else {
        ElMessage.error("代码为空");
    }
}
async function download(b?: boolean) {
    const n = activity.value.find(e => e.ID === activityid.value)?.isdownload
    if (prop.isAdmin === 0) {
        if (n !== 2) {
            ElMessage.info('没有权限')
            return
        }

    }
    const data1: string[][] = [
        ["用户", "题目ID", "答题时间", "题目名称", "AC", "代码"],
    ];
    if (!b) {
        userquestion.value.forEach((e) => {
            let {
                user,
                matchquestion,
                questionid,
                info,
                context,
                createdAt,
            } = e;
            const contextarr = []
            for (let v = 0; v < String(context).length; v = v + 30000) {
                if (v === 0 && String(context).length > 30000) {
                    contextarr.push('本次提交代码过长超出Excel单元格限制，请拼接后续单元格组成代码')
                }
                contextarr.push(String(context).slice(v, v + 30000))
            }
            data1.push([
                String(user?.name),
                String(questionid),
                TimeYH(createdAt),
                String(matchquestion?.name),
                e.resultdata ? e.resultdata : '',
                ...contextarr,
            ]);
        });
    } else {
        const userid = userids.value;
        const formquery: Iobj<any> = {
            _limit: count1.value,
            _offset: 0,
            activityid: activityid.value,
            teamid: prop.data?.ID
        };
        if (userid) {
            formquery.userid = userid;
        } else {
            formquery.userid = getusers.value.map(e => e.value).filter(e => e)
        }
        if (times.value) {
            formquery.createdAt = {
                lt: times.value[1],
                gt: times.value[0],
            };
        }
        if (questionid.value) {
            Object.assign(formquery, {
                questionid: questionid.value,
            });
        }
        const { rows, count } = await asyncteamselectmatchuserquestion(
            Object.assign(formquery)
        );
        rows
            .forEach((e) => {
                let {
                    user,
                    matchquestion,
                    questionid,
                    context,
                    createdAt,
                } = e;
                const contextarr = []
                for (let v = 0; v < String(context).length; v = v + 30000) {
                    if (v === 0 && String(context).length > 30000) {
                        contextarr.push('本次提交代码过长超出Excel单元格限制，请拼接后续单元格组成代码')
                    }
                    contextarr.push(String(context).slice(v, v + 30000))
                }
                data1.push([
                    String(user?.name),
                    String(questionid),
                    TimeYH(createdAt),
                    String(matchquestion?.name),
                    e.resultdata ? e.resultdata : '',
                    ...contextarr,
                ]);
            });
    }
    if (data1.length > 1) {
        const team = activity.value.find((e) => e.ID === activityid.value);
        const name = team?.name ? team.name : "学生日志"
        getExceltodownload(data1, name);
    }
}
</script>

<style scoped>
.data2table {
    --el-table-border: #fff;
    --el-table-header-text-color: var(--color-43);
    --el-table-text-color: var(--color-43);
}

.el-main {
    border: 1px solid #d9d9d9;
    box-sizing: border-box;
    /* Depth 4 */

    box-shadow: 0px 0.3px 0.9px rgba(0, 0, 0, 0.1),
        0px 1.6px 3.6px rgba(0, 0, 0, 0.13);
    border-radius: 4px;
    background: #ffffff;
}

.core {
    text-align: right;
}

.core a {
    color: #666;
    text-decoration: none;
}

.core a:hover {
    color: #000;
}

.questionname {
    width: 93%;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
</style>

<style>
.data2table .cell {
    padding-left: 2px !important;
    padding-right: 2px !important;
}

.data2table .el-table__cell {
    padding-top: 6px !important;
    padding-bottom: 6px !important;
}

.data2table th.is-leaf.el-table__cell {
    border-bottom: 1px solid var(--color-c4) !important;
}
</style>